const app = getApp()
import util from '../../../../utils/util'
import {
  EdiDetail,
  EdiApply,
  GetSample
} from '../../../../config/api'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    model: 1,
    id:'',
    isDisabled: false,
    data:'',
    name:'',
    phone:'',
    idcard: [],
    revIdcard:[],
    hkbhome: [],
    hkbself: [],
    bankimg:[],
    count_idcard: 0,
    count_revIdcard: 0,
    count_hkbhome: 0,
    count_hkbself: 0,
    count_bankimg: 0,
    compressImgsSizeArr_idcard: [],
    compressImgsSizeArr_revIdcard: [],
    compressImgsSizeArr_hkbhome: [],
    compressImgsSizeArr_hkbself: [],
    compressImgsSizeArr_bankimg: [],
    flag: true,
    example: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let member = wx.getStorageSync('member')
    if (!member){
      wx.redirectTo({
        url: '/pages/register/register',
      })
      return;
    }
    let model = wx.getStorageSync('model')
    if (model) {
      this.setData({
        model
      })
    }

    if (options.id) {
      this.setData({
        id: options.id
      })
      util.apiRequest(EdiDetail, {
        id: options.id
      }, null).then(r => {
        console.log("详情：", r)
        this.data.idcard.push(r.data.data.idcard_img)
        this.data.revIdcard.push(r.data.data.idcard_reverse_img)
        this.data.hkbhome.push(r.data.data.hukouben_home_img)
        this.data.hkbself.push(r.data.data.hukouben_self_img)
        this.data.bankimg.push(r.data.data.bank_card)
        this.setData({
          data: r.data.data,
          name:r.data.data.name,
          phone:r.data.data.phone,
          idcard: this.data.idcard,
          revIdcard: this.data.revIdcard,
          hkbhome: this.data.hkbhome,
          hkbself: this.data.hkbself,
          bankimg: this.data.bankimg
        })
        if (r.data.data.status != 1) {
          this.setData({
            isDisabled:true
          })
        }
      })
    }
    this.getExample()
  },

  getExample() {
    let that = this;
    util.apiRequest(GetSample, null, null).then(r => {
      console.log("是咧：", r)
      that.setData({
        example: r.data.data
      })
    })
  },

  checkExample() {
    this.setData({
      flag: false,
    })
  },
  conceal() {
    this.setData({
      flag: true
    })
  },

  formSubmit(e) {
    let name = e.detail.value.name.replace(/(^\s*)|(\s*$)/g, "");
    if (!name) {
      wx.showToast({
        title: '请填写姓名',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    if (!(/^1[3456789]\d{9}$/.test(e.detail.value.phone))) {
      wx.showToast({
        title: '手机号码格式不对',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    if (this.data.idcard.length == 0) {
      wx.showToast({
        title: '请上传身份证正面',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    if (this.data.revIdcard.length == 0) {
      wx.showToast({
        title: '请上传身份证反面',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    if (this.data.hkbhome.length == 0) {
      wx.showToast({
        title: '请上传户口本首页',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    if (this.data.hkbself.length == 0) {
      wx.showToast({
        title: '请上传户口本本人页',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    if (this.data.bankimg.length == 0) {
      wx.showToast({
        title: '请上传银行卡照片',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    let member = wx.getStorageSync('member')
    let params = {
      uid: member.id,
      vollege_id: member.vollege_id,
      town_id: member.town_id,
      name: e.detail.value.name,
      phone: e.detail.value.phone,
      idcard_img: this.data.idcard[0],
      idcard_reverse_img:this.data.revIdcard[0],
      hukouben_home_img: this.data.hkbhome[0],
      hukouben_self_img: this.data.hkbself[0],
      bank_card: this.data.bankimg[0],
    }
    if (this.data.id) {
      params['id'] = this.data.id
    }
    console.log(params)
    util.apiRequest(EdiApply, params).then(r => {
      console.log("提交：", r)
      if (r.data.code == 1) {
        wx.showModal({
          showCancel: false,
          content: '提交成功！请在我的代办中查看代办进度。',
          success(res) {
            if (res.confirm) {
              wx.redirectTo({
                url: '/pages/mine/pension_records/pension_records',
              })
            }
          }
        })
      } else {
        wx.showToast({
          title: r.data.info,
          icon: 'none',
          duration: 2000
        })
      }
    })

    console.log('form发生了submit事件，携带数据为：', e.detail.value)
  },

  // 上传图片
  chooseImg: function(e) {
    //console.log('选择图片e', e)
    var that = this;
    var name = e.currentTarget.dataset.name;
    console.log("图片类型：", name)
    var imgs = this.data[name];
    let uploadFile = ''; //最后处理完，图片上传的图片地址

    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        //  console.log('图片', res.tempFilePaths)
        var tempFilePaths = res.tempFilePaths;
        // var imgs = [];
        wx.showLoading({
          title: '上传中',
        })
        for (let i = 0; i < tempFilePaths.length; i++) {
          let index = that.data.count;
          let canvasId = 'canvasId' + index; // canvas id
          console.log('canvasId', canvasId)
          //获得原始图片大小
          wx.getImageInfo({
            src: tempFilePaths[i],
            success(res) {
              console.log('原始图片r', res)
              var originWidth, originHeight;
              originHeight = res.height;
              originWidth = res.width;
              //压缩比例
              // 最大尺寸限制
              var maxWidth = 800,
                maxHeight = 600;
              // 目标尺寸
              var targetWidth = originWidth,
                targetHeight = originHeight;

              //等比例压缩，如果宽度大于高度，则宽度优先，否则高度优先
              if (originWidth > maxWidth || originHeight > maxHeight) {
                console.log('图片过大需要压缩')
                if (originWidth / originHeight > maxWidth / maxHeight) {
                  // 要求宽度*(原生图片比例)=新图片尺寸
                  targetWidth = maxWidth;
                  targetHeight = Math.round(maxWidth * (originHeight / originWidth));
                } else {
                  targetHeight = maxHeight;
                  targetWidth = Math.round(maxHeight * (originWidth / originHeight));
                }
              }

              //更新canvas大小
              let compressObj = {},
                // compressImgsSizeArr = that.data.compressImgsSizeArr;
                compressImgsSizeArr = that.data["compressImgsSizeArr_" + name];
              compressObj['index'] = index;
              compressObj['cw'] = targetWidth;
              compressObj['ch'] = targetHeight;
              compressImgsSizeArr.push(compressObj)

              that.setData({
                ["compressImgsSizeArr_" + name]: compressImgsSizeArr
                //compressImgsSizeArr: compressImgsSizeArr
              });

              //尝试压缩文件，创建 canvas
              var ctx = wx.createCanvasContext(canvasId);
              ctx.clearRect(0, 0, targetWidth, targetHeight);
              ctx.drawImage(tempFilePaths[i], 0, 0, targetWidth, targetHeight);

              //console.log('图片尺寸数组', that.data.compressImgsSizeArr)

              //保存图片
              ctx.draw(false,
                setTimeout(function() {
                  wx.canvasToTempFilePath({
                    canvasId: canvasId,
                    width: targetWidth,
                    height: targetHeight,
                    destWidth: targetWidth,
                    destHeight: targetHeight,
                    quality: 0.4,
                    success: (res) => {
                      console.log('压缩后', res)
                      uploadFile = res.tempFilePath;
                      wx.uploadFile({
                        url: app.globalData.baseURL + '/api/WxProgramApi/upload',
                        filePath: uploadFile,
                        name: 'file',
                        header: {
                          "Content-Type": "multipart/form-data"
                        },
                        formData: {
                          'file': tempFilePaths
                        },
                        success(res) {
                          console.log('图片上传成功', res)
                          let data = JSON.parse(res.data);
                          if (res.statusCode == 200) {
                            var imgSrc = data.data;
                            console.log('图片服务器地址', imgSrc)
                            that.data[name].push(imgSrc);
                            console.log('图片数组', imgs)
                            that.setData({
                              [name]: that.data[name]
                            })
                            console.log("that.data[name]:", that.data[name])
                            wx.hideLoading()
                          }
                        },
                        fail(res) {
                          console.log('上传失败')
                        }
                      })

                    },
                    fail: (err) => {
                      console.error(err)
                    }
                  }, this)
                }, 1000)
              );

            }
          })

          let count = ++that.data['count_' + name];
          console.log('++count', count)
          that.setData({
            ['count' + name]: count
          })
          //console.log('循环后count', that.data.count)
        }
      }
    });
  },

  // 删除图片
  deleteImg: function(e) {
    var name = e.currentTarget.dataset.name;
    var imgs = this.data[name];
    var compressImgsSizeArr = this.data["compressImgsSizeArr_" + name];
    var index = e.currentTarget.dataset.index;
    imgs.splice(index, 1);
    compressImgsSizeArr.splice(index, 1);
    this.setData({
      [name]: imgs,
      ["compressImgsSizeArr" + name]: compressImgsSizeArr
    })
  },

  // 预览图片
  previewImg: function(e) {
    let that = this;
    var name = e.currentTarget.dataset.name;
    //获取当前图片的下标
    var index = e.currentTarget.dataset.index;
    console.log('预览index', index)
    //所有图片
    var imgType = e.currentTarget.dataset.imgtype;
    var imgs = this.data[name];

    console.log('预览时imgs', imgs)
    console.log(imgs[index])
    wx.previewImage({
      //当前显示图片
      current: imgs[index],
      //所有图片
      urls: imgs
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})